/**
 * 
 */
package com.wontube.smr.conf;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.google.gson.Gson;
import com.wontube.client.extension.utils.FileUtils;

/**
 * @author yuechao
 *
 */
public final class LocalIPList implements Serializable {
	private static final long serialVersionUID = 2168415890890362349L;
	private static final Logger logger = LoggerFactory.getLogger(LocalIPList.class);
	public static final LocalIPList IPList = new LocalIPList();
	
	private List<String> ipList = new ArrayList<String>(5);

	private LocalIPList() {
	}
	
	public List<String> getIPList() {
		return this.ipList;
	}
	
	public void setIPList(List<String> value) {
		this.ipList = value;
	}
	
	public LocalIPList load(File file) {
		String json = "";
		try {
			json = FileUtils.readAllText(file);
		} catch (IOException ex) {
			logger.error(ex.toString());
		}
		
		LocalIPList list = new LocalIPList();
		if (!"".equals(json)) {
			Gson gson = new Gson();
			list = gson.fromJson(json, LocalIPList.class);
		}
		
		if (list.ipList.size() < 1) {
			String ip = "";
			try {
				ip = InetAddress.getLocalHost().getHostAddress();
			} catch (UnknownHostException e) {
				logger.error(e.toString());
			}
			
			list.ipList.add(ip);
		}
		
		this.ipList = list.ipList;
		
		if (logger.isInfoEnabled()) {
			StringBuilder sb = new StringBuilder("[");
			for (String ip : this.ipList) {
				if (sb.length() > 1) {
					sb.append(",");
				}
				sb.append(ip);
			}
			sb.append("]");
			logger.info("loaded local ips: {}", sb.toString());
		}
		
		return this;
	}
}